package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.query.RegionObject;
import cn.wolfcode.wolf2w.repository.DestinationRepository;
import cn.wolfcode.wolf2w.repository.RegionRepository;
import cn.wolfcode.wolf2w.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class RegionServiceImpl implements IRegionService {

    @Autowired
    private RegionRepository repository;
    @Autowired
    private MongoTemplate template;
    @Autowired
    private DestinationRepository disrepository;


    @Override
    public void update(Region region) {
        repository.save(region);
    }

    @Override
    public void save(Region region) {
        repository.save(region);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public Region get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Region> list() {
        return repository.findAll();
    }

    @Override
    public Page<Region> query(RegionObject qo) {

        Query query = new Query();

        long total = template.count(query, Region.class);
        if (total == 0) {
            return Page.empty();
        }

        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1,
                qo.getPageSize(), Sort.Direction.ASC, "_id");
        query.with(pageable);
        List<Region> regions = template.find(query, Region.class);
        return new PageImpl<>(regions, pageable, total);
    }

    @Override
    public void saveOrUpdate(Region region) {
        if (StringUtils.hasLength(region.getId())) {
            repository.save(region);
        } else {
            region.setId(null);
            template.insert(region);
        }
    }

    @Override
    public void changeHotValue(Integer hot, String id) {
//        Region region = repository.findById(id).orElse(null);
//        region.setIshot(hot);
//        repository.save(region);
        //______________________________________________
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.set("ishot", hot);
        template.updateMulti(query, update, Region.class);
    }

    @Override
    public List<Region> getIsHot() {
        List<Region> regions = repository.findByIshotOrderBySequence(1);
        return regions;
    }


}
